package com.yale.elasticsearch.service.base;

import com.yale.elasticsearch.dto.UserInfoDTO;
import com.yale.elasticsearch.model.entity.UserInfo;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.json.JsonData;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 文档操作
 */
@Slf4j
@Service
public class DocumentService {

    @Resource
    private ElasticsearchClient elasticsearchClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 检查文档是否存在
     *
     * @param id
     * @param indexName
     * @return
     */
    public Object existsDocument(String id, String indexName) {
        Object result = "";
        try {
            // 创建 GetRequest 请求对象
            GetRequest getRequest = GetRequest.of(r -> r
                    .index(indexName)
                    .id(id)
            );

            // 执行请求，验证文档是否存在
            GetResponse<JsonData> getResponse = elasticsearchClient.get(getRequest, JsonData.class);

            // 检查文档是否存在
            boolean isExist = getResponse.found();
            log.info("文档是否存在：{}" , getResponse.found());

            // 根据具体业务逻辑返回不同结果，这里为了方便直接将结果返回
            result = isExist;
        } catch (IOException e) {
            log.error("Error executing get request: {}" , e.getMessage());
        }
        return result;
    }

    /**
     * 获取文档信息
     *
     * @param id
     * @param indexName
     * @return
     */
    public Object getDocument(String id, String indexName) {
        Object result = "";
        try {
            // 创建 GetRequest 请求对象
            GetRequest getRequest = GetRequest.of(r -> r
                    .index(indexName)
                    .id(id)
            );

            // 执行请求，获取文档信息
            GetResponse<JsonData> getResponse = elasticsearchClient.get(getRequest, JsonData.class);

            // 检查文档是否存在
            if (getResponse.found()) {
                // 将 JSON 转换成对象
                UserInfo userInfo = JSON.parseObject(getResponse.source().toJson().toString(), UserInfo.class);
                log.info("用户信息：{}" , JSON.toJSONString(userInfo));
                result = JSON.toJSONString(userInfo);
            } else {
                log.info("文档不存在：{}" + id);
                result = "Document does not exist";
            }
        } catch (IOException e) {
            log.error("Error executing get request: {}" , e.getMessage());
        }
        return result;
    }

    /**
     * 增加文档
     *
     * @param userInfoDTO
     * @return
     */
    public Object addDocument(UserInfoDTO userInfoDTO) {
        Object result = "";
        try {
            // 将对象转换为 JsonData
            JsonData jsonData = JsonData.of(userInfoDTO);
            Long id = stringRedisTemplate.opsForValue().increment(userInfoDTO.getIndexName() + "_id", 1);
            // 创建索引请求对象
            IndexRequest<JsonData> indexRequest = IndexRequest.of(i -> i
                    .index(userInfoDTO.getIndexName())
                    .id(String.valueOf(id))
                    .document(jsonData)
            );

            // 执行增加文档
            IndexResponse response = elasticsearchClient.index(indexRequest);

            // 输出创建状态
            log.info("创建状态：{}" , response.result());
            result = response.result();
        } catch (IOException e) {
            log.error("Error executing index request: {}" , e.getMessage());
        }
        return result;
    }

    /**
     * 更新文档
     *
     * @param userInfoDTO
     * @return
     */
    public Object updateDocument(UserInfoDTO userInfoDTO) {
        Object result = "";
        try {
            // 将对象转换为 JsonData
            JsonData jsonData = JsonData.of(userInfoDTO);

            // 创建更新请求对象
            UpdateRequest<UserInfo, JsonData> updateRequest = UpdateRequest.of(u -> u
                    .index(userInfoDTO.getIndexName())
                    .id(String.valueOf(userInfoDTO.getId()))
                    .doc(jsonData)
            );

            // 执行更新文档
            UpdateResponse<UserInfo> response = elasticsearchClient.update(updateRequest, JsonData.class);

            // 输出更新状态
            log.info("更新状态：{}" , response.result());
            result = response.result();
        } catch (IOException e) {
            log.error("Error executing update request: {}" , e.getMessage());
        }
        return result;
    }

    /**
     * 删除文档
     *
     * @param id
     * @param indexName
     * @return
     */
    public Object deleteDocument(String id, String indexName) {
        Object result = "";
        try {
            // 创建删除请求对象
            DeleteRequest deleteRequest = DeleteRequest.of(d -> d
                    .index(indexName)
                    .id(id)
            );

            // 执行删除文档
            DeleteResponse response = elasticsearchClient.delete(deleteRequest);

            // 输出删除状态
            log.info("删除状态：{}" , response.result());
            result = response.result();
        } catch (IOException e) {
            log.error("Error executing delete request: {}" , e.getMessage());
        }
        return result;
    }
}
